/*================================================================
*   Copyright (C) 2018  All rights reserved.
*   
*   Filename：tcp_server.c
*   Creator ：pony
*   Create  date：2018-01-28
*   Description：
*
================================================================*/

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>

#define MAXSIZE 64
#define SERVER_PORT 6666
int main(int argc, char** argv)
{
	struct sockaddr_in servaddr;
	struct sockaddr_in cliaddr; 
	int listenfd,clienfd;
	int len;
	socklen_t cliaddr_len;
	char buff[MAXSIZE];
	char str[INET_ADDRSTRLEN];
	listenfd = socket(AF_INET, SOCK_STREAM,0);
	if(listenfd == -1)
	{
		perror("socket");
		exit(-1);
	}
	printf("create sock success!\n");
	//填充地址协议族
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERVER_PORT);

	//bind
	if(bind(listenfd,(struct sockaddr *)&servaddr,sizeof(struct sockaddr)) != 0)
	{
		perror("bind");
		exit(-1);
	}
	printf("bind sock success!\n");
	//listent
	if(listen(listenfd,128) != 0)
	{
		perror("listen");
		exit(-1);
	}
	printf("listen........\n");
	while(1)
	{
		bzero(&buff,sizeof(buff));
		cliaddr_len = sizeof(cliaddr);
		//accept
		clienfd = accept(listenfd,(struct sockaddr *)&cliaddr,&cliaddr_len);
		if(-1 == clienfd)	
		{
			printf("clientfd %d\n",clienfd);
			perror("accept");
			continue;
		}
		printf("success accept......fd:%d\n",clienfd);
		len = read(clienfd,buff,sizeof(buff)-1);
		if(len > 0)
		{
			printf("accept from IP:%s Port:%d  content[%d]-->%s\n ",
					inet_ntop(AF_INET,&cliaddr.sin_addr,str,sizeof(str)),
					ntohs(cliaddr.sin_port),len,buff);
		}
		else if(len == 0)
		{
			close(clienfd);
			printf("close clienfd1\n");
			//break;
		}
		else
		{
			perror("read");
		}

		close(clienfd);
		printf("close clienfd2\n");

	}

	close(listenfd);
	printf("close listenfd\n");	

	return 0;
}
